package logic

import (
	"context"
	"github.com/pkg/errors"
	"newwater/app/identity/cmd/rpc/identity"
	"newwater/app/user/model"
	"newwater/common/tool"
	"newwater/common/xerr"

	"newwater/app/user/cmd/rpc/internal/svc"
	"newwater/app/user/cmd/rpc/user"

	"github.com/tal-tech/go-zero/core/logx"
)
var ErrUserNoExistsError = xerr.NewErrMsg("用户不存在")
var ErrGenerateTokenError = xerr.NewErrMsg("生成token失败")
var ErrUsernamePwdError = xerr.NewErrMsg("账号或密码不正确")
type LoginByPhoneLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginByPhoneLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginByPhoneLogic {
	return &LoginByPhoneLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginByPhoneLogic) LoginByPhone(in *user.LoginByPhoneReq) (*user.UserReply, error) {
	// todo: add your logic here and delete this line
	var userId int64
	var err error

	userId, err = l.LoginByMobilePhone(in.Phone, in.Password)

	if err != nil {
		return nil, err
	}

	resp, err := l.svcCtx.IdentityRpc.GenerateToken(l.ctx, &identity.GenerateTokenReq{
		UserId: userId,
	})
	if err != nil {
		return nil, errors.Wrapf(ErrGenerateTokenError, "IdentityRpc.GenerateToken userId : %d", userId)
	}

	jwt := new(user.JwtToken)
	jwt.AccessToken=  resp.AccessToken
	jwt.AccessExpire=  resp.AccessExpire
	jwt.RefreshAfter=  resp.RefreshAfter

	return &user.UserReply{
		Jwttoken: jwt,
	}, nil
}
func (l *LoginByPhoneLogic) LoginByMobilePhone(phone ,password string) (int64,error){
	user, err := l.svcCtx.WaterUser.FindOneByMobile(phone)
	if err != nil && err != model.ErrNotFound {
		return 0, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "根据手机号查询用户信息失败，phone:%s,err:%v", phone, err)
	}
	if user == nil {
		return 0, errors.Wrapf(ErrUserNoExistsError, "mobile:%s", phone)
	}
	//转换md5
	if(tool.Md5ByString(password) != user.Password){
		return 0, errors.Wrap(ErrUsernamePwdError, "密码匹配出错")
	}
	return user.UserId,nil
}